package top.zosoft.server;

import io.netty.bootstrap.AbstractBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoopGroup;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import top.zosoft.builder.ServerBuilder;

import java.util.concurrent.ExecutorService;

/**
 * base server
 * @author neal
 * @date 2023/12/26  10:07
 */
@Slf4j
@NoArgsConstructor
public abstract class Server {
    protected EventLoopGroup bossGroup;
    protected EventLoopGroup workerGroup;
    protected ExecutorService businessService;
    //是否启动标志
    protected boolean isRunning;
    public ServerBuilder config;

    protected Server(ServerBuilder config){
        this.config = config;
    }

    protected abstract AbstractBootstrap initialize();

    public synchronized boolean start() {
        if(isRunning){
            log.warn("=>服务:{},在端口:{},已经运行", config.name, config.port);
            return isRunning;
        }
        AbstractBootstrap bootstrap = initialize();
        ChannelFuture future = bootstrap.bind(config.port).awaitUninterruptibly();
        if (isRunning = future.isSuccess()) {
            log.info("=>服务:{},在端口:{},启动成功！", config.name, config.port);
            return isRunning;
        }

        if (future.cause() != null) {
            log.error("服务启动失败", future.cause());
        }
        future.channel().closeFuture().addListener(channelFuture -> {
            if(isRunning){
                stop();
            }
        });
        return isRunning;
    }
    public synchronized void stop() {
        isRunning = false;
        bossGroup.shutdownGracefully();
        if (workerGroup != null) {
            workerGroup.shutdownGracefully();
        }
        if (businessService != null) {
            businessService.shutdown();
        }
        log.warn("=>服务:{},在端口:{},已经停止！", config.name, config.port);
    }
}
